package com.sync.utils.project.demo.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.sync.utils.common.constant.HeaderConstants;
import com.sync.utils.common.base.controller.impl.BaseControllerImpl;
import com.sync.utils.common.utils.TokenUtils;
import com.sync.utils.framework.entity.AccessToken;
import com.sync.utils.framework.entity.AppInfo;
import com.sync.utils.framework.entity.UserInfo;
import com.sync.utils.common.enums.ResultCodeEnum;
import com.sync.utils.common.exception.BusinessException;
import com.sync.utils.common.exception.UserLoginException;
import com.sync.utils.framework.result.R;
import com.sync.utils.common.utils.MD5Util;
import com.sync.utils.project.demo.pojo.LoginUser;
import com.sync.utils.project.demo.pojo.UserDto;
import com.sync.utils.project.demo.pojo.UserRes;
import com.sync.utils.project.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * TODO
 *
 * @Author YWF
 * @Date 2022/1/26 11:49
 */

@RestController
@RequestMapping("/user/")
public class TokenController extends BaseControllerImpl {

    @Autowired
    private UserService userService;

    @Value("${job.beginTime}")
    private String beginTime;

    /**
     * 游客登录
     * @return
     */
    @PostMapping(value = "vLogin")
    public R<AccessToken> visitorLogin() {
        String appKey = request.getHeader(HeaderConstants.X_APPKEY);
        logger.info("appKey:{}",appKey);
        // 1. 根据appKey获取缓存中的密钥appSecret
        AppInfo appInfo = redisCache.hget(appInfoCacheKey,appKey);
        // 3. 如果正确生成一个token保存到redis中，如果错误返回错误信息
        AccessToken accessToken = TokenUtils.saveToken(0, appInfo, null);

        return R.ok().data(accessToken);
    }


    /**
     * 用户登录
     *
     * @Author YWF
     * @Date  2023/3/27 18:42
     * @Param [loginUser]
     **/
    @PostMapping(value = "login")
    public R<UserInfo> userLogin(@RequestBody LoginUser loginUser) {
        String appKey = request.getHeader(HeaderConstants.X_APPKEY);
        // 根据用户名查询密码, 并比较密码(密码可以RSA加密一下)
        String account = loginUser.getAccount();
        String passWord = loginUser.getPassWord();
        UserDto userDto = userService.getUserInfo(account);
        if (ObjectUtil.isEmpty(userDto)){
            throw new UserLoginException(ResultCodeEnum.USER_NOT_EXISTS);
        }
        String pwd = passWord + userDto.getSalt();
        String passwordMD5 = MD5Util.encode(pwd);
        logger.info("pwd:{},密码加密后：{}",pwd,passwordMD5);
        if (!passwordMD5.equals(userDto.getPassword())){
            throw new BusinessException(ResultCodeEnum.PWD_ERROR);
        }
        // 2. 保存Token
        AppInfo appInfo = redisCache.hget(appInfoCacheKey,appKey);
        UserInfo userInfo= BeanUtil.copyProperties(userDto,UserInfo.class);
        AccessToken accessToken = TokenUtils.saveToken(1, appInfo, userInfo);
        userInfo.setAccessToken(accessToken);
        return R.ok().data(userInfo);
    }

    /**
     * 用户退出
     * @date 2023/4/2 11:41
     */
    @PostMapping("logout")
    public R logout(){
        String token = request.getHeader(HeaderConstants.X_TOKEN);
        TokenUtils.destoryToken(token);
        return R.ok();
    }

    /**
     * 用户信息查询
     * @date 2023/4/2 11:42
     */
    @GetMapping("info")
    public R getUserInfo(){
        String token = request.getHeader(HeaderConstants.X_TOKEN);
        UserInfo tokenUser = TokenUtils.getTokenUser(token);
        return R.ok().data(tokenUser);
    }

    @Scheduled(cron = "${job.runTime}")
    public void syncJob(){
        logger.info("配置文件开始时间：{}",beginTime);
        logger.info("定时任务运行,{}",new Date().getTime());
    }

}
